// utils/router.ts
import { useRouter } from 'vue-router'
import { qiankunWindow } from 'vite-plugin-qiankun/es/helper'
import type { RouteLocationRaw } from 'vue-router'
import { routePush, closeCurrentTab } from '@/utils/qiankunUtils'
import { useCache } from '@/hooks/web/useCache'
import { CommonQianKunEnum } from './constants'

const { wsCache } = useCache()
const BASE_PREFIX = wsCache.get(CommonQianKunEnum.BASER_ROUTE_PREFIX)

function addPrefix(location: RouteLocationRaw): RouteLocationRaw {
  if (!qiankunWindow.__POWERED_BY_QIANKUN__) return location

  // 1. 字符串路径情况
  if (typeof location === 'string') {
    return `${BASE_PREFIX}${location.startsWith('/') ? '' : '/'}${location}`
  }

  // 2. 对象形式路径
  if (typeof location === 'object') {
    return {
      ...location,
      path: location.path
        ? `${BASE_PREFIX}${location.path.startsWith('/') ? '' : '/'}${location.path}`
        : undefined
      // 注意：name 路由不需要处理，hash/query 等保持不变
    }
  }

  return location
}

export function useQianKunRouter() {
  const router = useRouter()

  return {
    ...router,
    push: (location: RouteLocationRaw) => router.push(addPrefix(location)),
    pushTab: (location: RouteLocationRaw) => routePush(addPrefix(location)),
    closeTab: closeCurrentTab,
    replace: (location: RouteLocationRaw) => router.replace(addPrefix(location)),
    resolve: (location: RouteLocationRaw) => router.resolve(addPrefix(location))
  }
}
